package cn.lg.soar.common.util.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * Long序列化(超过js精度范围自动转成字符串)
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class LongAutoSerializer extends JsonSerializer<Long> {

    private static final long max = 9_007_199_254_740_992L;

    public static final LongAutoSerializer instance = new LongAutoSerializer();

    private LongAutoSerializer(){}

    @Override
    public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (value > LongAutoSerializer.max || value < -LongAutoSerializer.max) {
            jsonGenerator.writeString(value.toString());
            return;
        }
        jsonGenerator.writeNumber(value);
    }
}
